<template>
  <div @viewappear="onViewappear">
    <template v-if="loaded">
      <template v-for="item in tabItems">
        <embed :src="item.src"
               v-if="!item.pushOpen"
               :key="item.index"
               type="weex"
               :style="{ visibility: item.show ? 'visible' : 'hidden', display: item.show ? 'block' : 'none'}"
               class="content"
        ></embed>
      </template>
      <div class="tabbar">
        <div class="tabbar-circle-wrapper">
          <div class="tabbar-circle"></div>
        </div>
        <div class="tabbar-bg" :style="{backgroundColor: tabbarBgColor, borderTopColor: tabbarBorderColor}"></div>
        <div class="tabbar-inner">
          <template v-for="(tabItem, idx) in tabItems">
            <div class="tabitem-container" @click="select(idx)" v-if="tabItem.title" v-bind:key="idx">
              <template v-if="idx === 2">
                <div class="tabitem-icon-circle-wrapper">
                  <div class="tabitem-icon-circle">
                    <image :src="tabItem.image" class="tabitem-icon-circle-icon tabitem-tab-icon-show" v-bind:key="tabItem.image"></image>
                    <image :src="tabItem.selectedImage" :class="['tabitem-tab-icon', tabItem.selected && 'tabitem-tab-icon-show']"
                           v-bind:key="tabItem.selectedImage"></image>
                  </div>
                </div>
                <text :style="{ color: tabItem.titleColor }" class="tabitem-tab-text">{{tabItem.title}}</text>
              </template>
              <template v-else>
                <div class="tabitem-icon-wrapper">
                  <image :src="tabItem.image" class="tabitem-tab-icon tabitem-tab-icon-show" v-bind:key="tabItem.image"></image>
                  <image :src="tabItem.selectedImage" :class="['tabitem-tab-icon', tabItem.selected && 'tabitem-tab-icon-show']"
                         v-bind:key="tabItem.selectedImage"></image>
                </div>
                <text :style="{ color: tabItem.titleColor }" class="tabitem-tab-text">{{tabItem.title}}</text>
              </template>
            </div>
          </template>
        </div>
      </div>
      <div class="boot-page" :style="{width: width + 'px', height: height + 'px'}" v-if="!bootPageHidden">
        <slider class="boot-page-slider" @change="bootPageSliderChange" :infinite="false"
                :style="{width: width + 'px', height: height + 'px'}" interval="5000" :auto-play="false">
          <div class="boot-page-adv" v-bind:key="pic.picUrl" v-for="pic in bootPagePicList"
                :style="{width: width + 'px', height: height + 'px'}" @click="jumpPagep(pic)">
            <image class="boot-page-adv-img" resize="cover" :style="{width: width + 'px', height: height + 'px'}"
                   :src="pic.picUrl"></image>
          </div>
          <indicator class="boot-page-slider-indicator"></indicator>
        </slider>
        <text class="boot-page-timeout" @click="hideBootPage" v-if="bootPageCountDownShown">{{bootPageTimeout ? bootPageTimeout + '跳过' : '进入' }}</text>
        <div class="boot-page-enter" v-if="bootPageEnterShown">
          <text class="boot-page-enter-btn" @click="hideBootPage">{{bootPageEnterBtnText}}</text>
        </div>
      </div>
      <div class="network-less-panel" v-if="networkLess">
        <text class="network-less-tip">您的网络好像被火星人偷走了:(</text>
        <text class="btn btn-default btn-md" @click="boot()">重新加载</text>
      </div>
      <home-popup :show="homePopupShow" ref="homePopup"></home-popup>
    </template>
    <page-loading :loaded="loaded"></page-loading>
    <wxc-mask height="600"
              width="550"
              duration="200"
              mask-bg-color="#FFFFFF"
              border-radius="20"
              :has-animation="hasAnimation"
              :has-overlay="true"
              :show-close="true"
              :show="clipboardDetectDialogShow"
              @wxcMaskSetHidden="searchMaskSetHidden">
      <div class="search-detect">
        <div class="search-detect-heading">
          <text class="search-detect-title">您是否需要搜索如下关键字</text>
        </div>
        <div class="search-detect-body">
          <div class="search-detect-text-wrapper">
            <text class="search-detect-text">{{searchKeywords}}</text>
          </div>
          <text class="btn btn-large search-detect-btn-main btn-primary" @click="search('TAOBAO')">搜淘宝</text>
        </div>
        <div class="search-detect-footer">
          <div class="search-detect-others">
            <div class="search-detect-others-btn" @click="search('JD')">
              <image class="search-detect-others-btn-icon" :src="jdIcon"></image>
              <text class="search-detect-others-btn-text">京东</text>
            </div>
            <div class="search-detect-others-btn" @click="search('PDD')">
              <image class="search-detect-others-btn-icon" :src="pddIcon"></image>
              <text class="search-detect-others-btn-text">拼多多</text>
            </div>
          </div>
        </div>
      </div>
    </wxc-mask>
    <wxc-dialog title="新版本升级"
                :content="upgradeContent"
                :show="upgradeDialogShow"
                :single="false"
                :show-no-prompt="false"
                confirm-text="立即升级"
                @wxcDialogCancelBtnClicked="upgradeDialogCancelBtnClicked"
                @wxcDialogConfirmBtnClicked="upgradeDialogConfirmBtnClicked">
    </wxc-dialog>
  </div>
</template>

<style lang="scss">
  @import "./sass/index";
  @import "./sass/var";
  @import "./sass/buttons";
  .network-less {
    &-panel {
      position: fixed;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: #ffffff;
      justify-content: center;
      align-items: center;
    }
    &-tip {
      font-size: 30px;
      color: $color-warning;
      margin-bottom: 20px;
    }
  }
  .flex-row {
    flex-direction: row;
  }
  .item-container {
    width: 750px;
  }
  .search-detect {
    &-heading {
      height: 100px;
      @include border-bottom(1, solid, #ddd);
      background-color: #fdfdfd;
      border-top-left-radius: 20px;
      border-top-right-radius: 20px;
      flex-direction: row;
      align-items: center;
      justify-content: center;
    }
    &-body {
      justify-content: center;
      align-items: center;
    }
    &-footer {

    }
    &-title {
      font-size: 32px;
      color: $color-warning;
      line-height: 50px;
    }
    &-text {
      &-wrapper {
        height: 300px;
        padding: 0 30px;
        align-items: center;
        justify-content: center;
      }
      font-size: 30px;
      color: $color;
      line-height: 36px;
    }
    &-btn-main {
      height: 70px;
      line-height: 70px;
      border-radius: 70px;
      font-size: 32px;
      flex: 1;
      width: 480px;
    }
    &-others {
      flex-direction: row;
      justify-content: space-between;
      padding: 20px 30px 0 ;
      &-btn {
        flex: 1;
        text-align: center;
        height: 100px;
        align-items: center;
        justify-content: center;
        &-text {
          font-size: 26px;
          color: $color-muted;
        }
        &-icon {
          width: 50px;
          height: 50px;
        }
      }
    }
  }
  .boot-page {
    background-color: #e4e4e4;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 0;
    &-slider {
      position: relative;
      &-indicator {
        height: 40px;
        item-size: 15px;
        item-color: rgba(205, 205, 205, 0.75);
        item-selected-color: #fff;
        position: absolute;
        bottom: 80px;
        left: 0;
        right: 0;
      }
    }
    &-timeout {
      $size: 100px;
      position: absolute;
      top: 60px;
      right: 20px;
      border-radius: $size;
      height: $size;
      background-color: rgba(0, 0, 0, 0.64);
      width: $size;
      line-height: $size;
      color: #FFFFFF;
      font-size: 24px;
      text-align: center;
    }
    &-enter {
      position: absolute;
      bottom: 80px;
      left: 0;
      right: 0;
      justify-content: center;
      align-items: center;
      &-btn {
        background-color: #FFFFFF;
        height: 90px;
        padding: 0 50px;
        line-height: 90px;
        border-radius: 100px;
        color: $color;
        font-size: 40px;
      }
    }
  }
</style>

<script>
import {WxcDialog, WxcMask} from 'weex-ui'
let urlPath = require('./include/url-path')
let login = require('./include/login')
let api = require('./include/api')
let modal = weex.requireModule('modal')
let broadcastKeys = require('./include/broadcast-channel-keys')
let bundleJsService = weex.requireModule('bundleJsService')
let storageKeys = require('./include/storage-keys')
let storage = require('./include/xstorage')
let pageJump = require('./include/page-jump')
let config = require('./include/app-config')
let theme = require('./include/theme')
let clipboard = weex.requireModule('clipboard')
let navigator = require('./include/xnavigator')
let DEFAULT_BG_COLOR = '#fff'
let DEFAULT_BORDER_COLOR = '#ddd'
let BroadcastChannel = require('./include/broadcast-channel')
let loginBroadcastChannel = new BroadcastChannel(broadcastKeys.LOGIN)
let platform = require('./include/platform')
let utils = weex.requireModule('utils')
let TABBAR_STYLE = {
  dark: {
    bgColor: '#1A1B20',
    selectedColor: '#fff',
    color: '#959598',
    borderColor: '#1A1B20'
  },
  light: {
    bgColor: DEFAULT_BG_COLOR,
    selectedColor: theme.tabbar.selectedColor,
    color: theme.tabbar.color,
    borderColor: DEFAULT_BORDER_COLOR
  }
}
module.exports = {
  mixins: [
    require('./mixin/page-loading')
  ],
  components: {
    WxcDialog,
    WxcMask,
    'x-image': require('./components/x-image.vue'),
    'animation': require('./components/animation.vue'),
    'home-popup': require('./components/home-popup.vue')
  },

  data: function () {
    return {
      contentHeight: (weex.config.env.deviceHeight - 88) * 750 / weex.config.env.deviceWidth,
      tabItems: [],
      iosShow: false,
      searchKeywords: '',
      clipboardDetectContent: '',
      clipboardDetectDialogShow: false,
      detectClipboardTimeout: 0,
      width: 750,
      height: 1330,
      networkLess: false,
      bootPagePicList: [],
      bootPageTimeout: 10,
      hasAnimation: true,
      bootPageHidden: false,
      bootPageCountDownShown: false,
      bootPageEnterShown: false,
      bootPageEnterBtnText: '开启进入',
      jdIcon: urlPath.assets('images/icon/platform/JD.png'),
      pddIcon: urlPath.assets('images/icon/platform/PDD.png?v=3'),
      currentTabIndex: 0,
      tabbarNavList: [],
      tabbarBgColor: DEFAULT_BG_COLOR,
      tabbarBorderColor: DEFAULT_BORDER_COLOR,
      homePopupShow: false,
      upgradeDialogShow: false,
      upgradeContent: '',
      upgradeUrl: ''
    }
  },
  created () {
    let globalEvent = weex.requireModule('globalEvent')
    globalEvent.addEventListener('weixinAuth', function (params) {
      // modal.alert({message: JSON.stringify(params)})
      let bc = new BroadcastChannel(broadcastKeys.WEIXIN_AUTH)
      bc.postMessage(params)
    })
    globalEvent.addEventListener('notification', userInfo => {
      this.handleNotification(userInfo)
    })
    if (weex.isRegisteredModule('pushService')) {
      let pushService = weex.requireModule('pushService')
      pushService.userInfo(userInfo => {
        this.handleNotification(userInfo)
      })
      // pushService.deviceToken(token => {
      //   modal.alert({message: token})
      // })
      // pushService.bindId('TEST_TAG', 'tag')
      // pushService.bindId('TEST_Account', 'account')
    }
    loginBroadcastChannel.onmessage = (e) => {
      if (e.data) {
        this.$refs.homePopup.detect()
      }
    }
  },
  mounted () {
    this.height = weex.config.env.deviceHeight * 750 / weex.config.env.deviceWidth
    this.boot()
  },
  methods: {
    bootPageTimeoutCountDown () {
      this.bootPageTimeout--
      setTimeout(() => {
        if (this.bootPageTimeout > 0) {
          this.bootPageTimeoutCountDown()
        } else {
          this.hideBootPage()
        }
      }, 1000)
      // this.networkLessTimeout = setTimeout(() => {
      //   this.networkLess = true
      // }, 3000)
    },
    upgradeDialogCancelBtnClicked () {
      this.upgradeDialogShow = false
    },
    upgradeDialogConfirmBtnClicked () {
      try {
        utils.openURL(this.upgradeUrl)
      } catch (e) {
        modal.alert({message: e.toLocaleString()})
      }
    },
    boot () {
      api.boot({
        platform: weex.config.env.platform.toUpperCase(),
        version: weex.config.env.appVersion
      }).done(rs => {
        let data = rs.data
        this.upgradeUrl = data.upgradeUrl
        // modal.alert({message: JSON.stringify(data)})
        if (weex.config.env.appVersion !== data.latestAppVersion && data.bundleJsPackage.showUpdate) {
          this.upgradeContent = '新版本（' + data.latestAppVersion + '）已经发布，请更新!'
          this.upgradeDialogShow = true
        }
        // modal.alert({message: JSON.stringify(data)})
        if (!data.login) {
          login.invalidate()
        }
        this.bootPagePicList = data.bootPagePicList
        if (!this.bootPagePicList || this.bootPagePicList.length === 0) {
          this.hideBootPage()
        }
        // data.tabbarNavList.push({
        //   title: '免单',
        //   src: 'free-charge-activity.js'
        // })
        this.tabbarNavList = data.tabbarNavList
        this.bootPageTimeout = data.bootPageTimeout
        this.bootPageCountDownShown = this.bootPageTimeout > 0
        this.bootPageEnterBtnText = this.bootPageEnterBtnText
        let bundleJsPackage = data.bundleJsPackage || {}
        this.iosShow = data.iosShow || !platform.isIOS()
        config.config({
          iosShow: this.iosShow || weex.config.env.debug,
          useCache: bundleJsPackage.useCache
        }).done(() => {
          if (platform.isWeb()) {
            this.init()
            return
          }
          storage.getItem(storageKeys.BUNDLE_JS_VERSION).done(version => {
            if (version === bundleJsPackage.version &&
              bundleJsPackage.useCache &&
              !weex.config.env.debug) {
              this.init()
            } else {
              // 更新
              bundleJsService.clean(() => {
                storage.setItem(storageKeys.BUNDLE_JS_VERSION, bundleJsPackage.version).done(() => {
                  this.init()
                })
              })
            }
          })
        })
      }).fail(rs => {
        this.networkLess = true
      })
    },
    bootPageSliderChange (e) {
      // modal.alert({message: JSON.stringify(e)});
      if (e.index === this.bootPagePicList.length - 1) {
        this.bootPageEnterShown = true
      } else {
        this.bootPageEnterShown = false
      }
    },
    hideBootPage () {
      this.bootPageHidden = true
      this.detect()
    },
    detect () {
      if (!this.detected) {
        this.detectPopup()
        this.detectClipboard()
      }
      this.detected = true
    },
    init () {
      this.networkLess = false
      // clearTimeout(this.networkLessTimeout)
      this.bootPageCountDownShown && this.bootPageTimeoutCountDown()
      // this.tabbarNavList.push({
      //   title: '11',
      //   page: 'hall11.js',
      //   pushOpen: true,
      //   style: '',
      //   selectedIconUrl: '',
      //   iconUrl: ''
      // })
      for (var i in this.tabbarNavList) {
        let nav = this.tabbarNavList[i];
        (function (nav) {
          this.tabItems.push({
            title: nav.title,
            image: nav.iconUrl,
            selectedImage: nav.selectedIconUrl,
            show: false,
            pushOpen: nav.pushOpen,
            _src: nav.page,
            style: nav.style
          })
        }).bind(this)(nav)
      }
      this.tabItems.forEach((item, i) => {
        urlPath.page(item._src, localJs => {
          item.src = localJs
          if (i === 0) {
            this.select(0)
          }
        })
      })
      this.loaded = true
      this.detectPopup()
    },
    detectPopup () {
      if (this.bootPageHidden && this.loaded) {
        // modal.alert({message: 123})
        this.homePopupShow = true
      }
    },
    handleNotification (userInfo) {
      if (!userInfo) {
        return
      }
      let data = userInfo.data
      if (!data) {
        return
      }
      pageJump(data)
    },
    tabbarItemClick: function (idx) {
      this.select(idx)
    },
    select: function (index) {
      // // navigator.push('order-pay.js?id=46')
      // if(index === 2) {
      //   navigator.push('shopcat.js')
      // }
      this.currentTabIndex = index
      var currentTabItem = this.tabItems[index]
      if (currentTabItem.pushOpen) {
        navigator.push(currentTabItem._src)
        return
      }
      let colorStyle = TABBAR_STYLE[(currentTabItem.style || 'light').toLowerCase()]
      this.tabbarBgColor = colorStyle.bgColor
      this.tabbarBorderColor = colorStyle.borderColor
      if (this.currentTabIndex === 0) {
        this.detectClipboard()
      }
      for (var i = 0; i < this.tabItems.length; i++) {
        var tabItem = this.tabItems[i]
        if (i === index) {
          tabItem.selected = true
          tabItem.titleColor = colorStyle.selectedColor
          tabItem.show = true
        } else {
          tabItem.selected = false
          tabItem.titleColor = colorStyle.color
          tabItem.show = false
        }
      }
    },
    detectClipboard () {
      if (!this.bootPageHidden) {
        return
      }
      clipboard.getString(ret => {
        let string = ret.data || ''
        if (string.trim().length > 0 && string.indexOf('\n') === -1) {
          this.searchKeywords = string
          this.clipboardDetectContent = string
          this.clipboardDetectDialogShow = true
        } else {
          this.clipboardDetectDialogShow = false
        }
      })
    },
    search (searchFrom) {
      navigator.push('commission-item-search.js?keywords=' + encodeURIComponent(this.searchKeywords) + '&searchFrom=' + searchFrom)
      clipboard.setString('')
    },
    searchMaskSetHidden () {
      this.clipboardDetectDialogShow = false
      clipboard.setString('')
    },
    jumpPagep (pic) {
      require('./include/page-jump')({
        page: pic.page,
        params: pic.params
      })
    },
    onViewappear () {
      if (this.currentTabIndex === 0 && this.bootPageHidden) {
        this.detectClipboard()
      }
    },
    onViewDisappear () {

    },
    cancelClipboardDetectCancel () {
      this.clipboardDetectDialogShow = false
      clipboard.setString('')
      this.detectClipboard()
    },
    cancelClipboardDetectConfirm () {
      clipboard.setString('')
      this.clipboardDetectDialogShow = false
      navigator.push('search.js?keywords=' + encodeURIComponent(this.searchKeywords))
      this.detectClipboard()
    }
  }
}
</script>
